package com.utility.httpclient;

import java.io.InputStream;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClient.BoundRequestBuilder;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.Response;

/**
 * http请求工具类
 */
public class HttpUtility {
	private static final String CHARSET = "UTF-8";
	/**
	 * 请求超时时间
	 */
	private static final int SO_TIMEOUT = 45000;
	/**
	 * 异步请求对象
	 */
	private static final AsyncHttpClient asyncHttpClient;


	/**
	 * 设置异步请求参数
	 */
	static {
		AsyncHttpClientConfig.Builder builder = new AsyncHttpClientConfig.Builder();
        builder.setConnectTimeout(SO_TIMEOUT);
        builder.setReadTimeout(SO_TIMEOUT);
        builder.setFollowRedirect(true);
        //支持302跳转
        builder.setStrict302Handling(true);
        builder.setMaxConnections(1000);
        builder.setMaxConnectionsPerHost(300);
        //支持http https
        builder.setAcceptAnyCertificate(true);
		asyncHttpClient = new AsyncHttpClient(builder.build());
	}
	
	/**
	 * GET请求
	 * @param url 接口地址，包含参数
	 * @param params 接口请求参数
	 * @param header 接口请求头部
	 * @return
	 * @throws ExecutionException 
	 * @throws InterruptedException 
	 */
	public static Response get(String url,Map<String,String> params,Map<String,String> header) {
		if(url == null || url.trim().length() == 0) {
			throw new RuntimeException("请求地址为空");
		}
		
		//在请求地址上拼接请求参数
		if(params != null && !params.isEmpty()) {
			StringBuilder serverUrl = new StringBuilder();
			Set<String> keySet = params.keySet();
			for(String key : keySet) {
				if(serverUrl.length() > 0) {
					serverUrl.append("&");
				}
				serverUrl.append(key);
				serverUrl.append("=");
				serverUrl.append(params.get(key));
			}
			if(url.indexOf("?") > 0) {
				url = url + serverUrl.toString();
			}else {
				url = url + "?" + serverUrl.toString();
			}
		}
		
		BoundRequestBuilder builder = asyncHttpClient.prepareGet(url);
		return request(url, header, builder);
	}
	
	/**
	 * 
	 * @param url
	 * @param param
	 * @param header
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static Response post(String url,Object param,Map<String,String> header) {
		if(url == null || url.trim().length() == 0) {
			throw new RuntimeException("请求地址为空");
		}
		
		BoundRequestBuilder builder = asyncHttpClient.preparePost(url);
		builder.setBodyEncoding(CHARSET);
		
		//判断参数格式，并设置请求参数
		if(param != null) {
			if(param instanceof String) {
				//请求参数为字符串格式
				builder.setBody(param.toString());
			}else if(param instanceof Map) {
				//请求参数为键值对格式
				Map map = (Map)param;
				Object[] keyArray = header.keySet().toArray();
		       	for(int index = 0;index < keyArray.length;index++){
		       		String key = keyArray[index].toString();
		       		Object value = map.get(key);
		       		if(value != null) {
		       			builder.addQueryParam(key, value.toString());
		       		}
		       	}
			}else if(param instanceof InputStream){
				//请求参数为数据流
				builder.setBody((InputStream)param);
			}else {
				//请求参数为实体类
				builder.setBody(JsonUtility.entityToStr(param));
			}
		}
		return request(url, header, builder);
	}
	
	/**
	 * 设置请求头部信息并返回请求结果
	 * @param url
	 * @param header
	 * @param builder
	 * @return
	 */
	private static Response request(String url,Map<String,String> header,BoundRequestBuilder builder) {
		//添加头部信息
		if(header != null && !header.isEmpty()){
       	 	Set<String> keySet = header.keySet();
       	 	for(String key : keySet){
       	 		builder = builder.setHeader(key, header.get(key));
       	 	}
		}
		
		try {
			return builder.execute().get();
		}catch(Exception e) {
			throw new RuntimeException(e);
		}
	}
}
